<?php

namespace addons\kuerp\model;

use think\Model;
use think\Exception;
use think\Db;
use think\Session;


class GoodsSales extends Model
{

    // 表名
    protected $name = 'kuerp_goods_sales';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'purchase_type_text',
        'purchase_time_text',
        // 'delivery_time_text',
        'pay_status_text',
        // 'check_status_text',
        'examine_status_text',
        'examine_time_text'
    ];
    

    
    public function getPurchaseTypeList()
    {
        return ['1' => __('Purchase_type 1'), '2' => __('Purchase_type 2')];
    }

    public function getPayStatusList()
    {
        return ['0' => __('Pay_status 0'), '1' => __('Pay_status 1'), '2' => __('Pay_status 2')];
    }

    public function getCheckStatusList()
    {
        return ['0' => __('Check_status 0'), '1' => __('Check_status 1')];
    }

    public function getExamineStatusList()
    {
        return ['0' => __('Examine_status 0'), '1' => __('Examine_status 1'), '2' => __('Examine_status 2')];
    }


    public function getPurchaseTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['purchase_type']) ? $data['purchase_type'] : '');
        $list = $this->getPurchaseTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPurchaseTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['purchase_time']) ? $data['purchase_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDeliveryTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delivery_time']) ? $data['delivery_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_status']) ? $data['check_status'] : '');
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getExamineStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['examine_status']) ? $data['examine_status'] : '');
        $list = $this->getExamineStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getExamineTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['examine_time']) ? $data['examine_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPurchaseTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeliveryTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setExamineTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function customers()
    {
        return $this->belongsTo('Customers', 'customers_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

	public function customer() {
		return $this->belongsTo(Customers::class, 'customers_id', 'id')->field('id,customer_name as name');
	}

    public function preparation()
    {
        return $this->belongsTo('app\admin\model\Admin', 'preparation_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function examine()
    {
        return $this->belongsTo('app\admin\model\Admin', 'examine_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function staffmember()
    {
        return $this->belongsTo('StaffMember', 'sale_user', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    //职员
	public function staff() {
		return $this->belongsTo(Staff::class, 'sale_user', 'id')->field('id,name,admin_id');
	}

    public function getAccountsList(){
        return (new Accounts())->where(['status'=>1])->select();
    }

    //创建合同
	public static function createContract($params,$siteGoodsCode) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name, 'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}
            // else{
            //     if($params[$name] === ''){
            //         $params[$name]= '';
            //     }
            // }
		}
        $sets= Db::name('kuerp_sets')->where(['name'=>['in',['examine','serial','batch', 'auxiliary']]])->column('is_checked', 'name');
        $examine = $sets['examine'];
        $set = $sets['serial'];
        $batch = $sets['batch'];
        $auxiliary_status = $sets['auxiliary'];
        if(empty($params['purchase_code'])){
            throw new Exception('请填写单据编号');
        }

        // $admin = Session::get('admin');
        $admin = Admin::info();
        if($params['pay_money']>0){
            if(empty($params['account'])){
                throw new Exception('请选择结算账户');
            }
            $all_now_pay_money = $now_pay_money = trim($params['pay_money']);
        }else{
            $all_now_pay_money = $now_pay_money = 0;
        }

        // $set= Db::name('kuerp_sets')->where(['name'=>'serial'])->value('is_checked');
        // $batch= Db::name('kuerp_sets')->where(['name'=>'batch'])->value('is_checked');
        // $auxiliary_status= Db::name('kuerp_sets')->where(['name'=>'auxiliary'])->value('is_checked');

        //销售员 当前登录为销售员时
        $sale_user = (int)$params['staff_id'] ?? 0;
        $sale_user_name = '';
        if (!$sale_user && $admin->is_sale && $admin->staff_member_id) {
            $sale_user = $admin->staff_member_id;
        }
        if(!empty($sale_user)){
            $sale_user_name = Db::name('kuerp_staff_member')->where(['id'=>$sale_user])->value('name');
        } else {
            throw new Exception('请选择结算账户');
        }
        $stores_id = $params['stores_id'] ?? 0;
        if(empty($stores_id) && $admin->is_sale && $admin->stores_info){
            $stores_id = $admin->stores_info['id'];
        }
        if(empty($stores_id)){
            throw new Exception('请选择仓库');
        }

        $data = [];
        $number = 0;$all_money = 0;$purchase_order_id = '';$tax_money=0;$money_tax_price=0;
        $back_money = 0;//返款金额
        $goods_number = 0;//询价条数
        $goodsList = Db::name('kuerp_goods')->where(['id'=>['in', array_column($params['product'], 'goods_id')]])->column('id,goods_code,serial,batch,auxiliary', 'id');
        foreach ($params['product'] as $k=>$v){
            if(!empty($v['goods_id'])){//有产品编号
                $goods_money = (float)$v['price'] * (float)$v['number'] - (float)$v['back_money'];
                $number += (float)$v['number'];
                $all_money += $goods_money;
                $tax_money += $goods_money;
                $money_tax_price += $goods_money;
                $back_money += (float)$v['back_money'];

                unset($pay_money);unset($pay_status);
                if($now_pay_money>0){
                    if($now_pay_money-$goods_money>=0){
                        $pay_status = 1;
                        $pay_money = $goods_money;
                        $now_pay_money -= $pay_money;
                    }else{
                        $pay_status = 2;
                        $pay_money = $now_pay_money;
                        $now_pay_money -= $now_pay_money;
                    }
                }

                $goods = $goodsList[$v['goods_id']];//Db::name('kuerp_goods')->where(['goods_code'=>$v])->field('id,serial,batch,auxiliary')->find();
                if (empty($goods)) {
                    throw new Exception('商品信息错误');
                }

                $serial_code = [];$period_period = [];
                if($goods['serial']==1 && $set==1){
                    if(empty($v['period']) && empty($params['serials'])){
                        throw new Exception('请输入锁编号或者点击数量栏选择锁号');
                    }
                    if (!empty($v['period'])) {
                        foreach ($v['period'] as $period_period_k=>$period_period_v){
                            $serial_code[] = $period_period_v['serial'];
                            $period_period[] = [
                                'serial' => $period_period_v['serial'],
                                'remark' => $period_period_v['remark'],
                            ];
                        }
                        $where = [];
                        $where['serial'] = ['in',$serial_code];
                        // if(!empty($params['purchase_id'][$k])){
                        //     $where['purchase_code'] = $params['purchase_id'][$k];
                        // }
                        $goods_serial = Db::name('kuerp_goods_serial')->where($where)->column('serial');
                        if(empty($goods_serial)){
                            throw new Exception('锁号不存在');
                        }
                        foreach ($serial_code as $serial_code_k=>$serial_code_v){
                            if(!in_array($serial_code_v,$goods_serial)){
                                throw new Exception($serial_code_v.'商品序列号不存在');
                            }
                        }
                        $goods_serials = Db::name('kuerp_goods_serial')->where(['status'=>['in',[2,3]],'serial'=>['in',$serial_code]])->column('serial');
                        if(!empty($goods_serials)){
                            $goods_serials = implode(',',$goods_serials);
                            throw new Exception('商品序列号'.$goods_serials.'已经待出库，不可重复出库');
                        }
                    }
                }

                if(in_array($goods['goods_code'],array_merge($siteGoodsCode['goods_code_caijia'],$siteGoodsCode['goods_code_xunjia']))){  //判断是否有材价通账号
                    if(empty($v['remark'])){
                        throw new Exception('请在商品'.$goods['goods_code'].'{备注栏}里面输入续费的材价通手机号');
                    }
                    if(empty($v['goods_number']) && in_array($goods['goods_code'],$siteGoodsCode['goods_code_xunjia'])){
                        throw new Exception('商品'.$goods['goods_code'].'未输入续费询价条数');
                    }
                    if(empty($v['year_number']) && in_array($goods['goods_code'],$siteGoodsCode['goods_code_caijia'])){
                        throw new Exception('商品'.$goods['goods_code'].'未输入续费时长');
                    }
                    if(!empty($v['remark'])){
                        $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$v['remark']));
                    }
                    $caijiaUserModel = new \app\common\model\caijiatong\User();
                    foreach ($remark as $remark_mobile){
                        $caijia_user = $caijiaUserModel->getUserInfo($remark_mobile);
                        if(!$caijia_user){
                            throw new Exception('材价通会员账号'.$remark_mobile.'不存在');
                        }
                    }

                }
                if(in_array($goods['goods_code'],$siteGoodsCode['goods_code_wls'])){  //判断网络锁是否存在
                    if(empty($v['remark'])){
                        throw new Exception('请在商品'.$goods['goods_code'].'{备注栏}里面输入续费的网络锁锁内码');
                    }
                    if(empty($v['year_number'])){
                        throw new Exception('商品'.$goods['goods_code'].'未输入续费时长');
                    }
                    if(!empty($v['remark'])){
                        $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$v['remark']));
                    }
                    $caijiaUserSoftwareModel = new \app\common\model\caijiatong\UserSoftware();
                    foreach ($remark as $remark_mobile){
                        if (((string)$remark_mobile)[0] != '2' && substr((string)$remark_mobile, 0, 5) != 'NBGV0') {
                            throw new Exception($remark_mobile.'不是网络锁');
                        }
                        $caijia_user = $caijiaUserSoftwareModel->getUsersoftwareInfo($remark_mobile);
                        if(!$caijia_user){
                            throw new Exception('网络锁'.$remark_mobile.'不存在');
                        }
                    }
                }

                // if(!empty($v['info_id'])){
                //     $unit_id_order = Db::name('kuerp_goods_sales_order_info')->where(['id'=>$v['info_id']])->value('goods_unit');
                //     if(!empty($unit_id_order) && $unit_id_order!=$v['unit_id']){
                //         throw new Exception('选择的商品单位与源销货订单不一致，保存失败');
                //     }
                // }

                //时间期限
                $start_date = $end_date = null;
                if(!empty($v['date_range'])){
                    $start_date = $v['date_range'][0];
                    $end_date = $v['date_range'][1];
                }
                //询价条数
                $goods_number += (float)($v['goods_number'] ?? 0);
                $data[] = [
                    'purchase_code'     =>  $params['purchase_code'],
                    'purchase_type'     =>  $params['purchase_type'] ?? 1,
                    'purchase_time'     =>  strtotime($params['purchase_time']),
                    'customers_id'      =>  (int)$params['customer_id'],//客户
                    'sale_user'         =>  $sale_user,//销售员
                    'sale_user_name'    =>  $sale_user_name,//销售员名称
                    'receiving_address' =>  $params['receiving_address'] ?? '',

                    'goods_code'        =>  $goods['goods_code'],//商品信息
                    'goods_note'        =>  '',
                    'goods_unit'        =>  (float)$v['unit_id'],
                    'goods_type'        =>  $v['goods_type'],//商品类型

                    'stores_id'         =>  $stores_id,
                    'allow_stock'       =>  0,
                    'order_info_id'     =>  0,
                    'number'            =>  (float)$v['number'],
                    'default_unit'      =>  (float)$v['unit_id'],
                    'basic_nmber'       =>  (float)$v['number'],
                    'unit_price'        =>  (float)$v['price'],
                    'cost_price'        =>  0,
                    'discount'          =>  0,
                    'dis_money'         =>  0,
                    'back_money'        =>  (float)$v['back_money'],
                    'all_money'         =>  $goods_money,
                    'remark'            =>  $v['remark'],

                    'goods_attr'        =>  0,
                    'tax_included'      =>  (float)$v['price'],
                    'tax_rate'          =>  0,
                    'tax_money'         =>  0,
                    'money_tax_price'   =>  $goods_money,

                    'batch_id'          => 0,
                    'batch_name'        => '',
                    'manufacture'       => 0,
                    'guarantee'         => 0,
                    'validity'          => 0,

                    'preferential_rate' =>  0,
                    'preferential_money'=>  0,
                    'real_money'        =>  $goods_money,
                    'purchase_money'    =>  0,
                    'preparation_id'    =>  $admin->id,
                    'operation_id'      =>  $admin->id,

                    'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                    'pay_money'         =>  isset($pay_money)?$pay_money:0,
                    'account'           =>  isset($pay_status)?$params['account']:0,

                    'purchase_order_id' =>  '',

                    'createtime'        => time(),
                    'updatetime'        => time(),
                    'period'            => $period_period ? serialize($period_period):'',
                    'serial_code'       => $serial_code,
                    'goods_batch_info'  => [],
                    'start_date'        => $start_date,
                    'end_date'          => $end_date,
                    'year_number'      => $v['year_number'] ?? 0,
                    'goods_number'      => $v['goods_number'] ?? 0,
                ];
            }
        }
        $preferential_money = (float)($params['preferential_money'] ?? 0);
        if(!empty($data)){
            if($all_now_pay_money>0){
                if($all_now_pay_money+$preferential_money-$money_tax_price>=0){
                    $pay_status = 1;
                    $pay_money = $money_tax_price-$preferential_money;
                }else{
                    $pay_status = 2;
                    $pay_money = $all_now_pay_money;
                }
            }

            $row = [
                'purchase_code'     =>  $params['purchase_code'],
                'purchase_type'     =>  $params['purchase_type'] ?? 1,
                'purchase_time'     =>  strtotime($params['purchase_time']),
                'customers_id'      =>  (int)$params['customer_id'],//客户
                'sale_user'         =>  $sale_user,//销售员
                'sale_user_name'    =>  $sale_user_name,//销售员名称
                'receiving_address' =>  $params['receiving_address'] ?? '',
                'customers_money'   =>  (float)($params['customers_money'] ?? 0),

                'number'            =>  $number,
                'all_money'         =>  $all_money,

                'tax_money'         =>  $tax_money,//税
                'money_tax_price'   =>  $money_tax_price,//价税合计
                'back_money'        =>  $back_money,//返款金额

                'preferential_rate' =>  (float)($params['preferential_rate'] ?? 0),
                'preferential_money'=>  (float)($params['preferential_money'] ?? 0),
                'real_money'        =>  $all_money,
                'purchase_money'    =>  (float)($params['costs'] ?? 0),
                'note'              =>  $params['remark'],
                'buy_type'          =>  $params['buy_type'] ?? '',
                'buy_version'       =>  $params['buy_version'] ?? '',
                'customers_users'   =>  $params['contacts_id'] ?? '',
                'serials'           =>  $params['serials'] ?? '',
                'lock_code'         =>  $params['lock_code'] ?? '',
                'receipt'           =>  $params['receipt'] ?? '',//票据
                'preparation_id'    =>  $admin->id,
                'operation_id'      =>  $admin->id,

                'arrears'           =>  $params['arrears'],
                'all_arrears'       =>  $params['all_arrears'],

                'purchase_order_id' =>  $purchase_order_id,

                'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                'pay_money'         =>  isset($pay_money)?$pay_money:0,
                'account'           =>  isset($pay_status)?$params['account']:0,
                'cost_data'         =>  isset($params['cost_data'])?$params['cost_data']:null,
                'goods_number'      => $goods_number,
                'createtime'        => time(),
                'updatetime'        => time(),
            ];
            //是否在审核流程中
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($admin->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    $row['examine_id'] = $admin->id;
                    $row['examine_adminids'] = $admin->id;
                    $row['check_history_uids'] = $admin->id;
                    $row['examine_index'] = $examine_index;
                }
            }
        } else {
            throw new Exception('请选择商品');
        }
        $model = new self;
        if($model->where(['purchase_code'=>trim($params['purchase_code'])])->find()){
            throw new Exception('单据编号已占用');
        }
        if($purchase_order_id){
            $order_id = Db::name('kuerp_goods_sales_order')->where(['purchase_code'=>$purchase_order_id])->value('id');
        }

        //附件记录开始
        $enclosureLog = [];
        if(isset($params['enclosure']) && !empty($params['enclosure'])){//选择了原始单据
            $enclosure = explode(',',$params['enclosure']);
            $enclosurelist = Db::name('kuerp_enclosure')->where(['id'=>['in',$params['enclosure']]])->select();
            if(sizeof($enclosurelist)!=sizeof($enclosure)){
                throw new Exception('选择的原始单据有误，请重新选择');
            }else{
                foreach ($enclosure as $k=>$v){
                    $enclosureLog[] = [
                        'enclosure_id'  => $v,
                        'purchase_code' => $params['purchase_code'],
                        'type'          => '5',
                    ];
                }
            }
            unset($params['enclosure']);
        }
        //附件记录结束

        $info_id = 0;//Db::name('kuerp_goods_sales_order_info')->where(['purchase_code'=>$params['purchase_code']])->column('id');
        $result = false;
        // Db::startTrans();
        // try {
            if(!empty($row)){
                $result = $model->insertGetId($row);
            }

            //添加附件记录
            if(!empty($enclosureLog)){
                foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                    $enclosureLog[$enclosureLog_k]['order_id'] = $result;
                }
                Db::name('kuerp_enclosure_log')->insertAll($enclosureLog);
            }
            //添加附件记录结束

            if(!empty($info_id)){
                Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
            }
            Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$params['purchase_code']])->delete();
            foreach ($data as $data_k=>$data_v){
                $goods_serial = $data_v['serial_code'];
                unset($data_v['serial_code']);

                $goods_batch_info = $data_v['goods_batch_info'];
                unset($data_v['goods_batch_info']);

                $purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v);

                //批次
                if($goods_batch_info){
                    $goods_batch_info['purchase_info_id'] = $purchase_id;
                    Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info);
                }

                if(!empty($goods_serial)){
                    Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
                        'status'=>'3',
                        'sale_id' => $purchase_id,
                        'sale_code' => $data_v['purchase_code']
                    ]);
                }

                if(!empty($data_v['order_info_id'])){
                    Db::name('kuerp_goods_saleord_info')->insert([
                        'order_id'=>$data_v['order_info_id'],
                        'purchase_id'=>$purchase_id,
                        'number'=>$data_v['number'],
                        'money'=>$data_v['pay_money'],
                        'all_money'=>$data_v['all_money'],
                        'tax_rate'=>$data_v['tax_rate'],
                        'tax_money'=>$data_v['tax_money'],
                        'money_tax_price'=>$data_v['money_tax_price']
                    ]);
                }
            }
            if(!empty($purchase_order_id)){
                if($result){
                    Db::name('kuerp_goods_saleord')->insert(['order_id'=>$order_id,'purchase_id'=>$result]);
                }
            }
        //     Db::commit();
        // } catch (Exception $e) {
        //     Db::rollback();
        //     $this->error($e->getMessage());
        // }
        // if (isset($result) && $result !== false) {
        //     if($examine!=1){
        //         try {
        //             $exa = $this->examine($result,1);
        //         } catch (Exception $e) {
        //         }
        //         if(!isset($exa) || $exa['status']!=1){
        //             $exa = $this->examine($result,1);
        //             try {
        //                 $this->del($result);
        //             } catch (Exception $e) {
        //             }
        //             $this->error($exa['msg']);
        //         }
        //     }
        //     $this->success();
        // } else {
        //     $this->error(__('No rows were inserted'));
        // }

        $flow = Flows::getFlowByTypes(Flows::CONTRACT_STATUS);
        //发送审批通知
        Flows::sendStepRecord($flow, Flows::CONTRACT_STATUS, $result);

		OperationLog::createLog(OperationLog::CONTRACT_TYPE, $result, '创建订单');

		return true;
	}
    //编辑合同
	public static function updateContract($params,$siteGoodsCode) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name, 'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}
            // else{
            //     if($params[$name] === ''){
            //         $params[$name]= '';
            //     }
            // }
		}
        $id = $params['id'];
        if (empty($id)) {
            throw new Exception('参数错误');
        }
        $row = self::find($id);
        if (empty($row)) {
            throw new Exception('数据不存在');
        }
        $sets= Db::name('kuerp_sets')->where(['name'=>['in',['examine','serial','batch', 'auxiliary']]])->column('is_checked', 'name');
        $examine = $sets['examine'];
        $set = $sets['serial'];
        $batch = $sets['batch'];
        $auxiliary_status = $sets['auxiliary'];
        if($row['examine_status']==1 && $examine==1){
            throw new Exception('不能编辑已审核的数据');
        }

        if(empty($params['purchase_code'])){
            throw new Exception('请填写单据编号');
        }

        // $admin = Session::get('admin');
        $admin = Admin::info();
        if($params['pay_money']>0){
            if(empty($params['account'])){
                throw new Exception('请选择结算账户');
            }
            $all_now_pay_money = $now_pay_money = trim($params['pay_money']);
        }else{
            $all_now_pay_money = $now_pay_money = 0;
        }

        // $set= Db::name('kuerp_sets')->where(['name'=>'serial'])->value('is_checked');
        // $batch= Db::name('kuerp_sets')->where(['name'=>'batch'])->value('is_checked');
        // $auxiliary_status= Db::name('kuerp_sets')->where(['name'=>'auxiliary'])->value('is_checked');

        //销售员 当前登录为销售员时
        $sale_user = (int)$params['staff_id'] ?? 0;
        $sale_user_name = '';
        if (!$sale_user && $admin->is_sale && $admin->staff_member_id) {
            $sale_user = $admin->staff_member_id;
        }
        if(!empty($sale_user)){
            $sale_user_name = Db::name('kuerp_staff_member')->where(['id'=>$sale_user])->value('name');
        } else {
            throw new Exception('请选择结算账户');
        }
        $stores_id = $params['stores_id'] ?? 0;
        if(empty($stores_id) && $admin->is_sale && $admin->stores_info){
            $stores_id = $admin->stores_info['id'];
        }
        if(empty($stores_id)){
            throw new Exception('请选择仓库');
        }

        $data = [];
        $number = 0;$all_money = 0;$purchase_order_id = '';$tax_money=0;$money_tax_price=0;
        $back_money = 0;//返款金额
        $goods_number = 0;//询价条数
        $goodsList = Db::name('kuerp_goods')->where(['id'=>['in', array_column($params['product'], 'goods_id')]])->column('id,goods_code,serial,batch,auxiliary', 'id');
        $info_ids = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->column('id');
        foreach ($params['product'] as $k=>$v){
            if(!empty($v['goods_id'])){//有产品编号
                $goods_money = (float)$v['price'] * (float)$v['number'] - (float)$v['back_money'];
                $number += (float)$v['number'];
                $all_money += $goods_money;
                $tax_money += $goods_money;
                $money_tax_price += $goods_money;
                $back_money += (float)$v['back_money'];

                unset($pay_money);unset($pay_status);
                if($now_pay_money>0){
                    if($now_pay_money-$goods_money>=0){
                        $pay_status = 1;
                        $pay_money = $goods_money;
                        $now_pay_money -= $pay_money;
                    }else{
                        $pay_status = 2;
                        $pay_money = $now_pay_money;
                        $now_pay_money -= $now_pay_money;
                    }
                }

                $goods = $goodsList[$v['goods_id']];//Db::name('kuerp_goods')->where(['goods_code'=>$v])->field('id,serial,batch,auxiliary')->find();
                if (empty($goods)) {
                    throw new Exception('商品信息错误');
                }

                $serial_code = [];$period_period = [];
                if($goods['serial']==1 && $set==1){
                    if(empty($v['period']) && empty($params['serials'])){
                        throw new Exception('请输入锁编号或者点击数量栏选择锁号');
                    }
                    if (!empty($v['period'])) {
                        foreach ($v['period'] as $period_period_k=>$period_period_v){
                            $serial_code[] = $period_period_v['serial'];
                            $period_period[] = [
                                'serial' => $period_period_v['serial'],
                                'remark' => $period_period_v['remark'],
                            ];
                        }
                        $where = [];
                        $where['serial'] = ['in',$serial_code];
                        // if(!empty($params['purchase_id'][$k])){
                        //     $where['purchase_code'] = $params['purchase_id'][$k];
                        // }
                        $goods_serial = Db::name('kuerp_goods_serial')->where($where)->column('serial');
                        if(empty($goods_serial)){
                            throw new Exception('锁号不存在');
                        }
                        foreach ($serial_code as $serial_code_k=>$serial_code_v){
                            if(!in_array($serial_code_v,$goods_serial)){
                                throw new Exception($serial_code_v.'商品序列号不存在');
                            }
                        }
                        $goods_serials = Db::name('kuerp_goods_serial')->where(['status'=>['in',[2,3]],'serial'=>['in',$serial_code], 'sale_id'=>['not in',$info_ids]])->column('serial');
                        if(!empty($goods_serials)){
                            $goods_serials = implode(',',$goods_serials);
                            throw new Exception('商品序列号'.$goods_serials.'已经待出库，不可重复出库');
                        }
                    }
                }

                if(in_array($goods['goods_code'],array_merge($siteGoodsCode['goods_code_caijia'],$siteGoodsCode['goods_code_xunjia']))){  //判断是否有材价通账号
                    if(empty($v['remark'])){
                        throw new Exception('请在商品'.$goods['goods_code'].'{备注栏}里面输入续费的材价通手机号');
                    }
                    if(empty($v['goods_number']) && in_array($goods['goods_code'],$siteGoodsCode['goods_code_xunjia'])){
                        throw new Exception('商品'.$goods['goods_code'].'未输入续费询价条数');
                    }
                    if(empty($v['year_number']) && in_array($goods['goods_code'],$siteGoodsCode['goods_code_caijia'])){
                        throw new Exception('商品'.$goods['goods_code'].'未输入续费时长');
                    }
                    if(!empty($v['remark'])){
                        $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$v['remark']));
                    }
                    $caijiaUserModel = new \app\common\model\caijiatong\User();
                    foreach ($remark as $remark_mobile){
                        $caijia_user = $caijiaUserModel->getUserInfo($remark_mobile);
                        if(!$caijia_user){
                            throw new Exception('材价通会员账号'.$remark_mobile.'不存在');
                        }
                    }

                }
                if(in_array($goods['goods_code'],$siteGoodsCode['goods_code_wls'])){  //判断网络锁是否存在
                    if(empty($v['remark'])){
                        throw new Exception('请在商品'.$goods['goods_code'].'{备注栏}里面输入续费的网络锁锁内码');
                    }
                    if(empty($v['year_number'])){
                        throw new Exception('商品'.$goods['goods_code'].'未输入续费时长');
                    }
                    if(!empty($v['remark'])){
                        $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$v['remark']));
                    }
                    $caijiaUserSoftwareModel = new \app\common\model\caijiatong\UserSoftware();
                    foreach ($remark as $remark_mobile){
                        if (((string)$remark_mobile)[0] != '2' && substr((string)$remark_mobile, 0, 5) != 'NBGV0') {
                            throw new Exception($remark_mobile.'不是网络锁');
                        }
                        $caijia_user = $caijiaUserSoftwareModel->getUsersoftwareInfo($remark_mobile);
                        if(!$caijia_user){
                            throw new Exception('网络锁'.$remark_mobile.'不存在');
                        }
                    }
                }

                // if(!empty($v['info_id'])){
                //     $unit_id_order = Db::name('kuerp_goods_sales_order_info')->where(['id'=>$v['info_id']])->value('goods_unit');
                //     if(!empty($unit_id_order) && $unit_id_order!=$v['unit_id']){
                //         throw new Exception('选择的商品单位与源销货订单不一致，保存失败');
                //     }
                // }
                //时间期限
                $start_date = $end_date = null;
                if(!empty($v['date_range'])){
                    $start_date = $v['date_range'][0];
                    $end_date = $v['date_range'][1];
                }
                //询价条数
                $goods_number += (float)($v['goods_number'] ?? 0);
                $data[] = [
                    'purchase_code'     =>  $params['purchase_code'],
                    'purchase_type'     =>  $params['purchase_type'] ?? 1,
                    'purchase_time'     =>  strtotime($params['purchase_time']),
                    'customers_id'      =>  (int)$params['customer_id'],//客户
                    'sale_user'         =>  $sale_user,//销售员
                    'sale_user_name'    =>  $sale_user_name,//销售员名称
                    'receiving_address' =>  $params['receiving_address'] ?? '',

                    'goods_code'        =>  $goods['goods_code'],//商品信息
                    'goods_note'        =>  '',
                    'goods_unit'        =>  (float)$v['unit_id'],
                    'goods_type'        =>  $v['goods_type'],//商品类型

                    'stores_id'         =>  $stores_id,
                    'allow_stock'       =>  0,
                    'order_info_id'     =>  0,
                    'number'            =>  (float)$v['number'],
                    'default_unit'      =>  (float)$v['unit_id'],
                    'basic_nmber'       =>  (float)$v['number'],
                    'unit_price'        =>  (float)$v['price'],
                    'cost_price'        =>  0,
                    'discount'          =>  0,
                    'dis_money'         =>  0,
                    'back_money'        =>  (float)$v['back_money'],
                    'all_money'         =>  $goods_money,
                    'remark'            =>  $v['remark'],

                    'goods_attr'        =>  0,
                    'tax_included'      =>  (float)$v['price'],
                    'tax_rate'          =>  0,
                    'tax_money'         =>  0,
                    'money_tax_price'   =>  $goods_money,

                    'batch_id'          => 0,
                    'batch_name'        => '',
                    'manufacture'       => 0,
                    'guarantee'         => 0,
                    'validity'          => 0,

                    'preferential_rate' =>  0,
                    'preferential_money'=>  0,
                    'real_money'        =>  $goods_money,
                    'purchase_money'    =>  0,
                    'preparation_id'    =>  $admin->id,
                    'operation_id'      =>  $admin->id,

                    'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                    'pay_money'         =>  isset($pay_money)?$pay_money:0,
                    'account'           =>  isset($pay_status) || $params['account'] ? $params['account']:0,

                    'purchase_order_id' =>  '',

                    'createtime'        => $row['createtime'],
                    'updatetime'        => time(),
                    'period'            => $period_period ? serialize($period_period):'',
                    'serial_code'       => $serial_code,
                    'goods_batch_info'  => [],
                    'start_date'        => $start_date,
                    'end_date'          => $end_date,
                    'year_number'      => $v['year_number'] ?? 0,
                    'goods_number'      => $v['goods_number'] ?? 0,
                ];
            }
        }
        $preferential_money = (float)($params['preferential_money'] ?? 0);
        if(!empty($data)){
            if($all_now_pay_money>0){
                if($all_now_pay_money+$preferential_money-$money_tax_price>=0){
                    $pay_status = 1;
                    $pay_money = $money_tax_price-$preferential_money;
                }else{
                    $pay_status = 2;
                    $pay_money = $all_now_pay_money;
                }
            }

            $rowdata = [
                'purchase_code'     =>  $params['purchase_code'],
                'purchase_type'     =>  $params['purchase_type'] ?? 1,
                'purchase_time'     =>  strtotime($params['purchase_time']),
                'customers_id'      =>  (int)$params['customer_id'],//客户
                'sale_user'         =>  $sale_user,//销售员
                'sale_user_name'    =>  $sale_user_name,//销售员名称
                'receiving_address' =>  $params['receiving_address'] ?? '',
                'customers_money'   =>  (float)($params['customers_money'] ?? 0),

                'number'            =>  $number,
                'all_money'         =>  $all_money,

                'tax_money'         =>  $tax_money,//税
                'money_tax_price'   =>  $money_tax_price,//价税合计
                'back_money'        =>  $back_money,//返款金额

                'preferential_rate' =>  (float)($params['preferential_rate'] ?? 0),
                'preferential_money'=>  (float)($params['preferential_money'] ?? 0),
                'real_money'        =>  $all_money,
                'purchase_money'    =>  (float)($params['costs'] ?? 0),
                'note'              =>  $params['remark'],
                'buy_type'          =>  $params['buy_type'] ?? '',
                'buy_version'       =>  $params['buy_version'] ?? '',
                'customers_users'   =>  $params['contacts_id'] ?? '',
                'serials'           =>  $params['serials'] ?? '',
                'lock_code'         =>  $params['lock_code'] ?? '',
                'receipt'           =>  $params['receipt'] ?? '',
                'preparation_id'    =>  $admin->id,
                'operation_id'      =>  $admin->id,

                'arrears'           =>  $params['arrears'],
                'all_arrears'       =>  $params['all_arrears'],

                'purchase_order_id' =>  $purchase_order_id,

                'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                'pay_money'         =>  isset($pay_money)?$pay_money:0,
                'account'           =>  isset($pay_status)?$params['account']:0,
                'cost_data'         =>  isset($params['cost_data'])?$params['cost_data']:null,
                'goods_number'      => $goods_number,
                'updatetime'        => time(),
            ];
            if ($row['examine_status'] == 2) {
                $rowdata['examine_status'] = 0;
                $rowdata['examine_id'] = 0;
                $rowdata['examine_time'] = 0;
                $rowdata['examine_remark'] = '';
            }
            //是否在审核流程中
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($admin->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    $rowdata['examine_id'] = $admin->id;
                    $rowdata['examine_adminids'] = $admin->id;
                    $rowdata['check_history_uids'] = $admin->id;
                    $rowdata['examine_index'] = $examine_index;
                }
            }
        } else {
            throw new Exception('请选择商品');
        }
        $model = new self;
        if($model->where(['purchase_code'=>trim($params['purchase_code']),'id'=>['<>',$id]])->find()){
            throw new Exception('单据编号已占用');
        }
        if($purchase_order_id){
            $order_id = Db::name('kuerp_goods_sales_order')->where(['purchase_code'=>$purchase_order_id])->value('id');
        }

        //附件记录开始
        $enclosureLog = [];
        if(isset($params['enclosure']) && !empty($params['enclosure'])){//选择了原始单据
            $enclosure = explode(',',$params['enclosure']);
            $enclosurelist = Db::name('kuerp_enclosure')->where(['id'=>['in',$params['enclosure']]])->select();
            if(sizeof($enclosurelist)!=sizeof($enclosure)){
                throw new Exception('选择的原始单据有误，请重新选择');
            }else{
                foreach ($enclosure as $k=>$v){
                    $enclosureLog[] = [
                        'enclosure_id'  => $v,
                        'purchase_code' => $params['purchase_code'],
                        'type'          => '5',
                    ];
                }
            }
            unset($params['enclosure']);
        }
        //附件记录结束

        $info_id = 0;//Db::name('kuerp_goods_sales_order_info')->where(['purchase_code'=>$params['purchase_code']])->column('id');
        $result = false;
        // Db::startTrans();
        // try {
            $result = $model->where(['id'=>$id])->update($rowdata);
            //添加附件记录
            // Db::name('kuerp_enclosure_log')->where(['order_id'=>$id,'type'=>'5'])->delete();
            if(!empty($enclosureLog)){
                foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                    $enclosureLog[$enclosureLog_k]['order_id'] = $id;
                }
                Db::name('kuerp_enclosure_log')->insertAll($enclosureLog);
            }
            //添加附件记录结束

            if(!empty($info_id)){
                Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
            }
            $purchase_exchange_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->column('id');
            Db::name('kuerp_goods_serial')->where(['sale_id'=>['in',$purchase_exchange_id],'status'=>'3'])->update([
                'status'=>'1',
            ]);
            Db::name('kuerp_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_exchange_id]])->delete();

            Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->delete();
            foreach ($data as $data_k=>$data_v){
                $goods_serial = $data_v['serial_code'];
                unset($data_v['serial_code']);

                $goods_batch_info = $data_v['goods_batch_info'];
                unset($data_v['goods_batch_info']);

                $purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v);

                //批次
                if($goods_batch_info){
                    $goods_batch_info['purchase_info_id'] = $purchase_id;
                    Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info);
                }

                if(!empty($goods_serial)){
                    Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
                        'status'=>'3',
                        'sale_id' => $purchase_id,
                        'sale_code' => $data_v['purchase_code']
                    ]);
                }

                if(!empty($data_v['order_info_id'])){
                    Db::name('kuerp_goods_saleord_info')->insert([
                        'order_id'=>$data_v['order_info_id'],
                        'purchase_id'=>$purchase_id,
                        'number'=>$data_v['number'],
                        'money'=>$data_v['pay_money'],
                        'all_money'=>$data_v['all_money'],
                        'tax_rate'=>$data_v['tax_rate'],
                        'tax_money'=>$data_v['tax_money'],
                        'money_tax_price'=>$data_v['money_tax_price']
                    ]);
                }
            }
            if(!empty($purchase_order_id)){
                if($result){
                    Db::name('kuerp_goods_saleord')->insert(['order_id'=>$order_id,'purchase_id'=>$result]);
                }
            }
        //     Db::commit();
        // } catch (Exception $e) {
        //     Db::rollback();
        //     $this->error($e->getMessage());
        // }

		// OperationLog::createLog(OperationLog::CONTRACT_TYPE, $result, '编辑订单');

		return true;
	}


}
